import React, { useState, useEffect } from 'react';
import { Button, Form, Input, Select, Upload, Switch, Row, Col, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import style from './AddUserDrawer.css';

const { Password } = Input;
let formLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}
function AddUserDrawer({ info, roleList, onClose, onDispatch }) {
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);
    const handleBeforeUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isJPEG = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        if (!(isJPG || isJPEG || isGIF || isPNG)) {
            message.error('只能上传JPG 、JPEG 、GIF、 PNG格式的图片');
        }
        const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isLt2M) {
            message.error('头像图片不能超过1M');
        }
        return false;
    };
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div className="ant-upload-text">上传</div>
        </div>
    );
    const handleChange = ({ fileList }) => setFileList(fileList);
    useEffect(() => {
        if (info.forEdit) {
            new Promise((resolve, reject)=>{
                onDispatch({ type:'permission/fetchUserDetail', payload:{ resolve, reject, employeeId:info.current.employeeId }})
            })
            .then((data)=>{
                let { employee, roleIds } = data;
                let { email, phone, userName, name, headshot, isActive, webRole, mobileRole } = employee || {};
                form.setFieldsValue({
                    userName,
                    name,
                    phone,
                    email,
                    isActive:isActive ? true : false,
                    webRole:webRole ? true : false,
                    mobileRole:mobileRole ? true : false,
                    roleIds
                });
                let config = window.g;
                setFileList([
                  {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    prevPath: headshot,
                    url: `https://${config.apiHost}/upload/getFileByPath?filePath=${headshot}`,
                  },
                ]);
                  
            })
        } else {
            form.setFieldsValue({
                isActive: true,
                webRole: true,
                mobileRole: true
            })
        }
    }, [info])
    return (
        <div>
            <Form
                {...formLayout}
                form={form}
            >
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item label='用户头像' rules={[{ required: true, message: '头像不能为空' }]}>
                            <Upload
                                listType="picture-card"
                                className={style['custom-upload']}
                                fileList={fileList}
                                onChange={handleChange}
                                onPreview={() => { }}
                                beforeUpload={handleBeforeUpload}
                            >
                                {fileList.length === 1 ? null : uploadButton}
                            </Upload>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item label='用户名' name='userName' rules={[{ required: true, message: '用户名不能为空' }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='真实姓名' name='name' rules={[{ required: true, message: '真实姓名不能为空' }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item label='电话' name='phone' rules={[{ required: true, message: '电话不能为空' }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='邮箱' name='email' rules={[{ required: true, message: '邮箱不能为空' }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
                {
                    info.forEdit 
                    ?
                    null
                    :
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item label='密码' name='password' rules={[{ required: true, message: '密码不能为空' }]}>
                                <Password />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label='确认密码' name='confirmPassword' rules={[{ required: true, message: '密码不能为空' }]}>
                                <Password />
                            </Form.Item>
                        </Col>
                    </Row>
                }
                
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item label='角色权限' name='roleIds' rules={[{ required: true, message: '角色权限不能为空' }]}>
                            <Select
                                mode='multiple'
                                maxTagCount={2}
                                options={roleList.map(i => ({ label: i.roleName, value: i.roleId }))}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='启用' name='isActive' valuePropName="checked" rules={[{ required: true, message: '请选择是否启用' }]}>
                            <Switch />
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item label='web端权限' name='webRole' valuePropName="checked" rules={[{ required: true, message: '请选择是否启用' }]}>
                            <Switch />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='移动端权限' name='mobileRole' valuePropName="checked" rules={[{ required: true, message: '请选择是否启用' }]}>
                            <Switch />
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <div style={{ textAlign: 'center', margin: '2rem 0' }}>
                <Button onClick={onClose} style={{ marginRight: '1rem' }}>取消</Button>
                <Button type='primary' onClick={() => {
                    form.validateFields()
                        .then(values => {
                            if (!fileList.length) {
                                message.info('请上传头像');
                                return;
                            }
                            if (values.password !== values.confirmPassword) {
                                message.info('两次密码输入不一致');
                                return;
                            }
                            values.isActive = values.isActive ? 1 : 0;
                            values.webRole = values.webRole ? 1 : 0;
                            values.mobileRole = values.mobileRole ? 1 : 0;
                            if (info.forEdit) {
                                values['employeeId'] = info.current.employeeId;
                                // 当更新时，上传文件变化时才更新headshot字段
                                if ( fileList[0].size ) {
                                    values.fileList = fileList.map(i=>i.originFileObj )
                                } else {
                                    values.fileList = null;
                                    values.headshot = null;
                                }  
                            } else {
                                values.fileList = fileList.map((i) =>
                                    i.size ? i.originFileObj : i,
                                );
                            }
                            new Promise((resolve, reject)=>{
                                onDispatch({ type:'permission/addUserAsync', payload:{ resolve, reject, values, forEdit:info.forEdit }})
                            })
                            .then(()=>{
                                message.success(`${info.forEdit ? '更新' : '添加'}用户成功`);
                                form.resetFields();
                                setFileList([]);
                                onClose();
                            })
                            .catch(msg=>message.error(msg));
                        })
                }}>确定</Button>
            </div>
        </div>
    )
}

export default AddUserDrawer;